package controller

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"mouth-project/model/mysql"
	"mouth-project/pkg"
	"mouth-project/request"
	"net/http"
	"time"
)

//用户注册

func UserRegister(c *gin.Context) {
	var userRegister request.UserRegisterReq
	if err := c.ShouldBindJSON(&userRegister); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg":  "服务器内部错误",
			"code": 500,
			"err":  err.Error(),
		})
		return
	}
	data := mysql.User{
		Username: userRegister.Username,
		Password: pkg.Md5(userRegister.Password), //注册时密码使用MD5加密
		Mobile:   userRegister.Mobile,
	}
	err := data.Register()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg":  "用户注册失败",
			"code": 400,
			"err":  err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":  "用户注册成功",
		"code": 200,
		"data": data,
	})
}

//用户登录

func UserLogin(c *gin.Context) {
	var userLogin request.UserLoginReq
	if err := c.ShouldBindJSON(&userLogin); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg":  "服务器内部错误",
			"code": 500,
			"err":  err.Error(),
		})
		return
	}
	data := mysql.User{Mobile: userLogin.Mobile}
	err := data.Login()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg":  "用户登录失败",
			"code": 400,
			"err":  err.Error(),
		})
		return
	}
	t := pkg.NewJWT("2206a")
	token := pkg.CustomClaims{
		ID:       data.ID,
		NickName: data.Username,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400,
			Subject:   "token失败",
		},
	}
	createToken, err := t.CreateToken(token)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg":  "生成token失败",
			"code": 400,
			"err":  err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":  "用户登录成功",
		"code": 200,
		"data": createToken,
	})
}
